<?php
class AdminController extends Zend_Controller_Action {
	
	public function init()
	{
		$message = '请登录';
	
		switch( $this->getRequest()->getActionName() ){ // TODO sortir les actions ci-dessous dans un controller "ouvert"
				
			case 'league':
			case 'modify-league':
			case 'save-league-team':
			case 'league-team':
				$access = false;
			    break;
			case 'login':
			case 'logout' :
			    $access = true;
			    break;   
		}
		if ( !$access ){
			$auth = Zend_Auth::getInstance();
			$auth->setStorage(new Zend_Auth_Storage_Session( 'Admin'));
			if ( $auth->hasIdentity() )
				$this->identity = $auth->getIdentity();
			else{
				$this->_redirect('/admin/login');
			}
		}
		
		$this->_helper->layout->setLayout('admin-layout');
	}
	
	public function loginAction() {
		
		$this->view->headScript()->appendFile ( '/js/jquery.js' );

		
		$form = $this->_manageFormLogin ();
		
		$this->view->formLogin = $form;
		
		$this->_helper->layout->setLayout('admin-login');
		
	}
	
	public function logoutAction()
	{
		Zend_Session::start(); //obligatoire pour que ça marche !
		//détruit les données de session coté serveur :
		Zend_Session::destroy();
		$this->_redirect('/');
	}
	
	public function leagueAction(){
		$this->_helper->actionStack('reduit', 'header');
		$this->_helper->actionStack('admin-options', 'left-menu');
		
		$model_league = new Model_League();
		$leagues = $model_league->getAllLeagues('desc');
		
		$this->view->leagues = $leagues;
	
		
		
	}
	

	public function newLeagueAction(){
		$this->_helper->actionStack('reduit', 'header');
		$this->_helper->actionStack('admin-options', 'left-menu');

		$form = new Form_CreateLeague();
		if($this->_request->isPost()  && $this->_request->getPost( 'cible' ) == 'create'){
			
			if ($form->isValid( $this->_request->getPost() )) {
				$model_league = new Model_League();
				$league_id = $model_league->createNewLeague($this->_request->getPost('league_name'),
						                                    $this->_request->getPost('team_count'));
				$this->_redirect('/admin/league-team/league-id/' . $league_id);
				
			}
			
		}	
		
		$this->view->form = $form;
	    
	
	}
	
	public function leagueCloseAction(){
		$this->_helper->actionStack('reduit', 'header');
		$this->_helper->actionStack('admin-options', 'left-menu');
		
		$league_id = (int)$this->_getParam('league-id');
		if($league_id!=0){
			$model_league = new Model_League();
			$league = $model_league->closeLeagueById($league_id);
			$this->_redirect('/admin/league/');
				
		}
		
	}
	public function modifyLeagueAction(){
		$this->_helper->actionStack('reduit', 'header');
		$this->_helper->actionStack('admin-options', 'left-menu');
	
		$league_id = (int)$this->_getParam('league-id');
		if($league_id!=0){
			$model_league = new Model_League();
			$league = $model_league->getLeagueById($league_id);			
			$this->view->league = $league;
			
			
		}
	
	}
	
	public function saveLeagueTeamAction(){
		$this->_helper->actionStack('reduit', 'header');
		$this->_helper->actionStack('admin-options', 'left-menu');
	
		$league_id = (int)$this->_getParam('league-id');
		if($league_id!=0){
			
			if($this->_request->isPost() ){
				$model_league = new Model_League();
				$league = $model_league->getLeagueById($league_id);
				
				$model_league_team = new Model_LeagueTeam();
				$count = 1;
				for($count=1;$count<$league->team_count +1;$count++){
					$model_league_team->modifyTeam($league_id,
							                    $count,
							                    $this->_request->getPost('team_'.$count), 
							                    $this->_request->getPost('user_'.$count));
				}
				
				
				$this->_redirect('/admin/league/');
			}else{
				
			}
			
				
				
		}
	
	}
	
	public function saveModifyLeagueTeamAction(){
		$this->_helper->actionStack('reduit', 'header');
		$this->_helper->actionStack('admin-options', 'left-menu');
	
		$league_id = (int)$this->_getParam('league-id');
		if($league_id!=0){
				
			if($this->_request->isPost() ){
				
				$model_league = new Model_League();
				$league = $model_league->getLeagueById($league_id);
	
				$model_league_team = new Model_LeagueTeam();
				$teams = $model_league_team->getTeamsByLeagueId($league_id);
				
				$model_game = new Model_Game();
				
				$count = 1;

				for($count=0;$count<$league->team_count;$count++){
					if(isset($teams[$count])){
						
						$model_game->clearGamesByLeagueIdAndTeamId($league_id,$teams[$count]['team_id']);
						$model_league_team->modifyTeam($league_id,
								$count+1,
								$this->_request->getPost('team_'.($count+1)),
								$this->_request->getPost('user_'.($count+1)));
						
					}else{ 
						$model_league_team->addTeam($league_id,
								$count+1,
								$this->_request->getPost('team_'.($count+1)),
								$this->_request->getPost('user_'.($count+1)));
						$model_game->addGamesByLeagueIdAndTeamId($league_id,$count+1);
						
					}
					/*
					if( teamuser existe)
						 delete all games of this user
						 update team
						 add games
				    else 
						update team 
						add games*/
						 
							
					
				}
	
			
				$this->_redirect('/admin/league/');
			}else{
	
			}
				
	
	
		}
	
	}
	
	public function leagueTeamAction(){
		$this->_helper->actionStack('reduit', 'header');
		$this->_helper->actionStack('admin-options', 'left-menu');
	
		$league_id = (int)$this->_getParam('league-id');
		if($league_id!=0){
			
				$model_league = new Model_League();
				$league = $model_league->getLeagueById($league_id);
			   
				$model_league_team = new Model_LeagueTeam();
				$teams = $model_league_team->getTeamsByLeagueId($league_id);
			
			    $model_user = new Model_User();
			    $users = $model_user->getAllActiveUsers('asc');
			    
			    $all_active_user_ids = "";
			    $all_user_names = "";
				$this->view->league = $league;
				$this->view->teams = $teams;
			     foreach($users as $user){
			     	$all_active_user_ids .=''.$user->id .',';
			     
			     }
			     foreach($users as $user){
			     	$all_user_names .='"'.$user->username .'",';
			     
			     }
			     $all_user_ids = substr($all_user_ids,0,-1);
			     $all_user_names = substr($all_user_names,0,-1);
			     
			$this->view->all_active_user_ids = $all_active_user_ids;
			$this->view->all_user_names = $all_user_names;
			
				
		}
	
	}
	
	public function modifyLeagueTeamAction(){
		$this->_helper->actionStack('reduit', 'header');
		$this->_helper->actionStack('admin-options', 'left-menu');
	
		$league_id = (int)$this->_getParam('league-id');
		if($league_id!=0){
				
			$model_league = new Model_League();
			$league = $model_league->getLeagueById($league_id);
	
			$model_league_team = new Model_LeagueTeam();
			$teams = $model_league_team->getTeamsByLeagueId($league_id);
				
			$model_user = new Model_User();
			$users = $model_user->getAllActiveUsers('asc');
			 
			$all_user_ids = "";
			$all_user_names = "";
			$this->view->league = $league;
			$this->view->teams = $teams;
			foreach($users as $user){
				$all_user_ids .=''.$user->id .',';
	
			}
			foreach($users as $user){
				$all_user_names .='"'.$user->username .'",';
	
			}
			$all_user_ids = substr($all_user_ids,0,-1);
			$all_user_names = substr($all_user_names,0,-1);
	
			$this->view->all_user_ids = $all_user_ids;
			$this->view->all_user_names = $all_user_names;
				
	
		}
	
	}
	
	public function deleteLeagueUserAction(){
		$league_id = (int)$this->_getParam('league-id');
		$team_id = (int)$this->_getParam('team-id');
		
		if($league_id!=0&&$team_id!=0){
			$model_league_team = new Model_LeagueTeam();
			
		    $model_league_team->deleteUserByLeagueIdAndTeamId($league_id,$team_id);
			$this->_redirect('/admin/league/');
		
		}
		
	}
	
	/////////////////////////////////////////////cup part
	
	public function cupAction(){
		$this->_helper->actionStack('reduit', 'header');
		$this->_helper->actionStack('admin-options', 'left-menu');
		
		$model_league = new Model_Cup();
		$cups = $model_league->getAllCups('desc');
		
		$this->view->cups = $cups;
		
		
	}
	
	public function newCupAction(){
		$this->_helper->actionStack('reduit', 'header');
		$this->_helper->actionStack('admin-options', 'left-menu');
	
		$form = new Form_CreateCup();
		if($this->_request->isPost()  && $this->_request->getPost( 'cible' ) == 'create'){
			
			if ($form->isValid( $this->_request->getPost() )) {
				$model_cup = new Model_Cup();
				$cup_id = $model_cup->createNewCup($this->_request->getPost('cup_name'),
						$this->_request->getPost('team_count'),$this->_request->getPost('group_count'));
				$this->_redirect('/admin/cup-team/cup-id/' . $cup_id);
	
			}
				
		}
	
		$this->view->form = $form;
		 
	
	}
	
	public function cupTeamAction(){
		$this->_helper->actionStack('reduit', 'header');
		$this->_helper->actionStack('admin-options', 'left-menu');
	
		$cup_id = (int)$this->_getParam('cup-id');
		if($cup_id!=0){
				
			$model_cup = new Model_Cup();
			$cup = $model_cup->getCupById($cup_id);
	
			$model_cup_team = new Model_CupTeam();
			$teams = $model_cup_team->getTeamsByCupId($cup_id);
				
			$grouped_teams = "";
		    foreach($teams as $team){
		    	$grouped_teams[$team['group_name']][] = $team;
		    }			
			$model_user = new Model_User();
			$users = $model_user->getAllActiveUsers('asc');
			 
			$all_active_user_ids = "";
			$all_user_names = "";
			$this->view->cup = $cup;
			$this->view->teams = $grouped_teams;
			foreach($users as $user){
				$all_active_user_ids .=''.$user->id .',';
	
			}
			foreach($users as $user){
				$all_user_names .='"'.$user->username .'",';
	
			}
			$all_user_ids = substr($all_user_ids,0,-1);
			$all_user_names = substr($all_user_names,0,-1);
	
			$this->view->all_active_user_ids = $all_active_user_ids;
			$this->view->all_user_names = $all_user_names;
				
	
		}
	
	}
	
	public function saveCupTeamAction(){
		$this->_helper->actionStack('reduit', 'header');
		$this->_helper->actionStack('admin-options', 'left-menu');
	
		$cup_id = (int)$this->_getParam('cup-id');
		if($cup_id!=0){
				
			if($this->_request->isPost() ){
				if($this->_request->getPost('cible')=='group-stage'){
					$model_cup = new Model_Cup();
					$cup = $model_cup->getCupById($cup_id);
					
					$model_cup_team = new Model_CupTeam();
					$count = 1;
					for($count=1;$count<$cup->team_count +1;$count++){
						$model_cup_team->modifyTeam($cup_id,
								$count,
								$this->_request->getPost('team_'.$count),
								$this->_request->getPost('user_'.$count));
					}
				}else if ($this->_request->getPost('cible')=='knock-out-stage'){
					
				}
				
	

				$this->_redirect('/admin/cup/');
			}else{
	
			}	
		}
	
	}
	
	public function deleteCupUserAction(){
		$cup_id = (int)$this->_getParam('cup-id');
		$team_id = (int)$this->_getParam('team-id');
	
		if($cup_id!=0&&$team_id!=0){
			$model_cup_team = new Model_CupTeam();
				
			$model_cup_team->deleteUserByCupIdAndTeamId($cup_id,$team_id);
			$this->_redirect('/admin/cup/');
	
		}
	
	}
	
	////////////////////////////////////////////user part
	
	public function userAction(){
		$this->_helper->actionStack('reduit', 'header');
		$this->_helper->actionStack('admin-options', 'left-menu');
		
		$model_user = new Model_User();
		$users = $model_user->getAllUsers('desc');
		
		$this->view->users = $users;
		
	}
	
	public function newUserAction(){
		$this->_helper->actionStack('reduit', 'header');
		$this->_helper->actionStack('admin-options', 'left-menu');
		
		$form = new Form_CreateUser();		
		$form->setAction($this->_request->getRequestUri());
		
		if($this->_request->isPost()  && $this->_request->getPost( 'cible' ) == 'create'){
	
			if ($form->isValid( $this->_request->getPost() )) {
	
				$model_user = new Model_User();
				$model_user->createNewUser($this->_request->getPost('username'),$this->_request->getPost('password'));
	            
	
				$this->_redirect('/admin/user/');
			}
	
		}
	
		$this->view->form = $form;
		
	}
	
	
	public function disactiveUserAction(){
		
		$user_id = (int)$this->_getParam('user-id');
		
		$model_user = new Model_User();
		$model_user->disactiveUserById($user_id);
		
		$this->_redirect('/admin/user/');
		
	}
	
	public function activeUserAction(){
	
		$user_id = (int)$this->_getParam('user-id');
	
		$model_user = new Model_User();
		$model_user->activeUserById($user_id);
	
		$this->_redirect('/admin/user/');
	
	}
	public function updateUserPasswordAction(){
		$this->_helper->actionStack('reduit', 'header');
		$this->_helper->actionStack('admin-options', 'left-menu');
	
		$user_id = (int)$this->_getParam('user-id');
		if($user_id!=0){
			$model_user = new Model_User();
			$user = $model_user->getUserById($user_id);
							
		}else{
			$this->_redirect('/admin/user/');
		}
		
		$form = new Form_CreateUser();		
		$form->setAction($this->_request->getRequestUri());
		
		$form->username->disabled = 'disabled';
		$form->username->setValue($user->username);
		$form->password->setLabel('新密码');
		$form->submit->setLabel('修改');
		
		if($this->_request->isPost()  && $this->_request->getPost( 'cible' ) == 'create'){
	
			if ($form->isValidPartial( $this->_request->getPost() )) {
	
				$model_user = new Model_User();
				$model_user->updateUserPassword($user_id,$this->_request->getPost('password'));
	            
	
				$this->_redirect('/admin/user/');
			}
	
		}
	
		$this->view->form = $form;
	}
	
	protected function _manageFormLogin() {
		$form = new Form_AdminLogin();
		$form->setAction( $this->_request->getRequestUri() );
		
		if ($this->_request->isPost() && $this->_request->getPost( 'cible' ) == 'login') {

			if ($form->isValid( $this->_request->getPost() )) {
				
				$authAdapter = $form->username->getValidator( 'LoginPasswordOk' )->getAuthAdapter();
				
				// récupère les informations du compte pour les mettre dans le
				// cookie :
				$data = $authAdapter->getResultRowObject ( null, 				// whitelist
					array (
							'password'
					) )				// blacklist
					;
				
				$formValues = $form->getValues();
				if ($formValues ['remember_me']) {
					$sessionLifetime = 121536000; // 4 ans environ
					                              
					// reglage du lifetime dans le cookie :
					Zend_Session::rememberMe ( $sessionLifetime );
					
					// reglage du lifetime dans les données de session
					Zend_Session::getSaveHandler()->setLifetime( $sessionLifetime, true );
				} else {
					// reglage du lifetime dans le cookie :
					Zend_Session::forgetMe(); // cookie de session
					                          
					// reglage du lifetime dans les données de session
					Zend_Session::getSaveHandler()->setLifetime( 86400, true ); // 24 heures
				}
				
				// écriture dans les données de session :
				$auth = Zend_Auth::getInstance();
				$auth->setStorage(new Zend_Auth_Storage_Session( 'Admin'));
				$auth->getStorage()->write( $data );
				
	
				
			
				// redirection :
				$redirectNamespace = new Zend_Session_Namespace( 'redirect' );
				$redirectUrl = $redirectNamespace->redirectUrl;
				
				if ($redirectUrl) {
					$redirectNamespace->redirectUrl = '/'; // on ne fait la
					                                       // redirection qu'une fois
					$this->_redirect( $redirectUrl );
				} else {
					$this->_redirect( '/admin/league' );
				}
			} else {
				
				// //fin de validation du compte mci
				$message = 'erreur dans le login ou mot de passe';
				//$this->_helper->messageNow( $message );
			}
		}
		return $form;
	}
	
	public function getAvailableUserIdsByLeagueIdAction(){
		if ($this->_request->isPost() ) {
			$model_league_team = new Model_LeagueTeam();
			$users = $model_league_team->getUsersByLeagueId($this->_request->getPost( 'league_id' ));
			
			$layout = Zend_Controller_Action_HelperBroker :: getStaticHelper('layout');
			$layout->disableLayout();
			
			$ids = '';
			foreach($users as $user){
				$ids .= $user['id'] .'-' ;				
			}
			print_r(substr($ids,0,-1));
			die();
			
		}else{
			
		}
	}
}
    
